<?php

use Phalcon\Mvc\Model;

class Users extends Model
{
    public $id;

    public $name;

    public $password;

    public $email;

    public static function setNewRecord($data)
    {
        if (empty($data)) {
            throw new \Phalcon\Exception('参数错误');
        }
        if (!isset($data['username']) || !isset($data['password'])) {
            throw new \Phalcon\Exception('缺少参数');
        }

        $data = array(
            'username' => $data['username'],
            'password' => $data['password'],
            'email'    => !empty($data['email']) ? $data['email'] : ' ',
        );
        $instance = new Users();
        $flag     = $instance->create($data);
        if ($flag) {
            return $instance->toArray();
        } else {
            return false;
        }
    }

    public static function getDataByFieldWithValue($value, $field = 'id')
    {
        $params = array(
            'conditions' => " {$field} = :{$field}: ",
            'bind'       => array(
                "{$field}" => $value,
            ),
        );
        $result = static::findFirst($params);
        if (is_object($result)) {
            return $result->toArray();
        } else {
            return false;
        }
    }

    public static function checkUsernameAndPassword($user, $pass)
    {
        $params = array(
            'conditions' => " username = :user: and password = :password: ",
            'bind'       => array(
                "user"     => $user,
                "password" => md5($pass),
            ),
        );
        $result = static::findFirst($params);
        if (is_object($result)) {
            return $result->toArray();
        } else {
            return false;
        }
    }
}
